package com.bwie.client;


import com.bwie.codec.CustomDecoder;
import com.bwie.codec.CustomEncoder;
import com.bwie.protocol.CustomProtocol;
import com.bwie.util.JT808Const;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PreDestroy;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;

/**
 * Netty TCP客户端
 */
@Component
public class NettyTcpClient {
    private static final Logger logger = LoggerFactory.getLogger(NettyTcpClient.class);

    @Value("${netty.tcp.server.host:localhost}")
    private String host;

    @Value("${netty.tcp.port:8089}")
    private int port;

    private EventLoopGroup group;
    private Channel channel;

    @Autowired
    TcpClientHandler tcpClientHandler;

    /**
     * 连接服务器
     */
    public void connect() throws InterruptedException {
        group = new NioEventLoopGroup();

        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(group)
                    .channel(NioSocketChannel.class)
                    .option(ChannelOption.TCP_NODELAY, true)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel ch) {
                            ChannelPipeline pipeline = ch.pipeline();

                            ByteBuf delimiter = Unpooled.copiedBuffer(new byte[]{JT808Const.PKG_DELIMITER});
                            pipeline.addLast("framer", new DelimiterBasedFrameDecoder(1024, true, delimiter));
                            pipeline.addLast(new CustomDecoder());
                            pipeline.addLast(new CustomEncoder());
                            pipeline.addLast(tcpClientHandler);
                        }
                    });

            // 连接服务器
            ChannelFuture future = bootstrap.connect(host, port).sync();
            logger.info("客户端已连接到服务器: {}:{}", host, port);

            // 保存通道引用
            channel = future.channel();
        } catch (Exception e) {
            logger.error("客户端连接失败", e);
            throw e;
        }
    }

    /**
     * 发送消息
     */
    public void sendMessage(String message) {
        if (channel == null || !channel.isActive()) {
            logger.error("通道未连接，无法发送消息");
            return;
        }

        logger.info("发送消息: {}", message);
        channel.writeAndFlush(new CustomProtocol(message));
    }

    /**
     * 关闭客户端
     */
    @PreDestroy
    public void close() {
        if (channel != null) {
            channel.close();
        }
        if (group != null) {
            group.shutdownGracefully();
        }
        logger.info("客户端已关闭");
    }

    public Boolean isOpen() {
    	return channel != null && channel.isOpen();
    }
}

